package com.lxyk.springcloud.service.impl;

import cn.hutool.core.util.IdUtil;
import com.lxyk.springcloud.service.PaymentService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

@Service
public class PaymentServiceImpl implements PaymentService {
    @Override
    public String paymentInfo_Ok(Integer id) {
        return "线程池："+Thread.currentThread().getName()+"paymentInfo_Ok,id="+id+"\t"+"哈哈哈";
    }

    @Override
    //熔断器超时案例
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
    })  //峰值3秒钟，超时出错，出错了就会调用兜底的方
    //需要一个兜底的方法
    public String paymentInfo_Timeout(Integer id) {//不超时走这个方法
        /*超时情况的服务降级*/
        int timeNumber=5;//5秒
        try {
            TimeUnit.SECONDS.sleep(timeNumber);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池："+Thread.currentThread().getName()+"paymentInfo_Timeout,id="+id+"\t"+"呜呜呜"+"耗时"+timeNumber+"秒";

        /*异常情况的服务降级 异常和超时都会调用兜底方法*/
        /*int age=10/0;
        return "线程池："+Thread.currentThread().getName()+"paymentInfo_Timeout,id="+id+"\t"+"呜呜呜"+"耗时";*/
    }



    //兜底方法
    public String paymentInfo_TimeOutHandler(Integer id){//超时走这个方法
        return "线程池："+Thread.currentThread().getName()+" 系统繁忙或者运行报错，请稍后再试,id：  "+id+"\t"+"┭┮﹏┭┮";
    }

    //熔断案例
    @Override
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
            //以下参数在 HystrixCommandProperties 类中有默认配置(四个配置结合起来意思是：在10秒内错误访问的次数为10次并且错误率到达60%时会触发熔断，这个接口就访问不到了)
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),  //是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),   //统计时间窗内请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),  //统计时间窗
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),  //在统计时间窗口期以内，请求失败率达到 60% 时进入熔断状态
    })
    public String paymentCircuitBreaker(@PathVariable("id") Integer id) {
        if (id<0){
            throw new RuntimeException("id不能为负数");//小于0，就会抛出异常，就会走兜底方法
        }
        String uuid = IdUtil.simpleUUID();
        return Thread.currentThread().getName()+"\t"+"调用成功，流水号"+uuid;
    }

    //paymentCircuitBreaker 的降级(兜底)方法
    public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id){
        return "id 不能负数，请稍候再试,(┬＿┬)/~~     id: " +id;
    }
}
